package com.peng.herostory.cmdhanlder;

import com.peng.herostory.Broadcaster;
import com.peng.herostory.model.User;
import com.peng.herostory.model.UserManager;
import com.peng.herostory.mq.MqProducer;
import com.peng.herostory.mq.RankMqMessage;
import com.peng.herostory.msg.GameMsgProtocol;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.AttributeKey;

public class UserAttackCmdHandler implements ICmdHandler<GameMsgProtocol.UserAttkCmd> {
    @Override
    public void handle(ChannelHandlerContext ctx, GameMsgProtocol.UserAttkCmd msg) {
        GameMsgProtocol.UserAttkResult.Builder attackResultBuilder = GameMsgProtocol.UserAttkResult.newBuilder();
        // 获取攻击者 Id
        Integer attackUserId = (Integer) ctx.channel().attr(AttributeKey.valueOf("userId")).get();
        if (null == attackUserId) {
            return;
        }
        //广播攻击动作
        GameMsgProtocol.UserAttkResult userAttackResult = attackResultBuilder
                .setTargetUserId(msg.getTargetUserId())
                .setAttkUserId(attackUserId)
                .build();
        Broadcaster.broadcast(userAttackResult);

        int subtractHp = 10;
        User user = UserManager.getUserById(msg.getTargetUserId());
        if (user == null) {
            return;
        }
        user.setHp(user.getHp() - subtractHp);
        //广播掉血消息
        broadcastSubtractHp(msg.getTargetUserId(), subtractHp);

        //血量小于0,广播用户死亡消息
        if (user.isGoDie()) {
            return;
        }
        if (user.getHp() <= 0) {
            broadcastUserToDie(msg.getTargetUserId());
            RankMqMessage message = new RankMqMessage(attackUserId, msg.getTargetUserId());
            MqProducer.getInstance().sendMsg("addRankScore", message);
            user.setGoDie(true);
        }


    }

    /**
     * 广播用户死亡消息
     *
     * @param targetUserId 目标用户id
     */
    private void broadcastUserToDie(int targetUserId) {
        if (targetUserId <= 0) {
            return;
        }
        GameMsgProtocol.UserDieResult result = GameMsgProtocol.UserDieResult.newBuilder().setTargetUserId(targetUserId).build();
        Broadcaster.broadcast(result);


    }

    /**
     * 广播减少hp消息
     *
     * @param targetUserId 目标用户id
     * @param hp           掉多少血
     */
    private void broadcastSubtractHp(int targetUserId, int hp) {
        if (targetUserId <= 0) {
            return;
        }
        if (hp <= 0) {
            return;
        }
        GameMsgProtocol.UserSubtractHpResult.Builder hpBuilder = GameMsgProtocol.UserSubtractHpResult.newBuilder();
        GameMsgProtocol.UserSubtractHpResult hpResult = hpBuilder.setSubtractHp(hp)
                .setTargetUserId(targetUserId)
                .build();
        Broadcaster.broadcast(hpResult);
    }
}
